package org.jcms.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jcms.model.Customer;
import org.jcms.service.AdminServiceI;
import org.jcms.service.CustomerServiceI;
import org.jcms.uitils.CookieUtil;
import org.json.JSONArray;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class CustomerBuildOrder extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public CustomerBuildOrder() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ApplicationContext ac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		CustomerServiceI customerServiceI = (CustomerServiceI) ac
				.getBean("customerServiceImpl");
		String retJson = "{\"error\":@err,\"msg\":\"@msg\"}";
		String err = "1";
		String msg = "";
		String cookieName = "bookTrolley";
		String cookiePath = request.getContextPath() + "/customer";
		Customer customer = (Customer) request.getSession().getAttribute(
				"customer");
		try {
			if (customer == null) {
				msg = "网页已过期";
				err = "2";
			} else {
				cookieName = cookieName + customer.getCustomerId();
				JSONArray jsonArray = CookieUtil.gets(cookieName, cookiePath,
						30 * 24 * 3600, request, response);
				if (jsonArray == null || jsonArray.length() == 0) {
					msg = "购物车中没有订购的教材，无法生成订单";
				} else {
					customerServiceI.buildOrder(customer, jsonArray, request,
							response);
					CookieUtil.dropCookie(cookieName, cookiePath, request, response);
					msg = "成功生成订单";
					err = "0";
				}
			}
		} catch (Exception e) {
			msg = "订单生成失败";
			e.printStackTrace();
		} finally {
			retJson = retJson.replace("@err", err);
			retJson = retJson.replace("@msg", msg);
			response.getOutputStream().write(retJson.getBytes("utf-8"));
		}
	}

	public void init() throws ServletException {

	}

}
